package com.doubao.util;

import com.alibaba.fastjson.JSONObject;
import com.doubao.protocol.Msg;
import com.doubao.server.NettyServer;
import com.doubao.user.User;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * channel 管理
 */
public class ChannelManage {

    private static final Logger log = LoggerFactory.getLogger(ChannelManage.class);
	/**
	 * 存储每一个客户端接入进来时的channel对象
	 */
	public static ChannelGroup group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    public static ConcurrentMap<String, Channel> userIdAndChannelMap = new ConcurrentHashMap<>();
    //存储对应关系
    public static ConcurrentMap<String, String> userIdAndChannelID = new ConcurrentHashMap<>();



	public static Boolean sendMsg( Msg msg) {
        try {
            Channel toChannel = getToChanel(msg);
            if(toChannel==null){
                log.error("toChannel is offer line !!");
                return false;
            }
            toChannel.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(msg)));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("send msg error!!");
        }
        return false;
    }

    public static boolean hasChannel(String id) {
        Channel channel = userIdAndChannelMap.get(id);
        if (channel == null) {
            return false;
        } else {
            return true;
        }
    }


    public static void initChannel(String uid,Channel channel) {
        userIdAndChannelMap.put(uid, channel);
        userIdAndChannelID.put(channel.id().asShortText(),uid);
    }


    public static void removeChannel(Channel channel) {
        group.remove(channel);
        String uid=userIdAndChannelID.get(channel.id().asShortText());
        if(uid!=null){
            userIdAndChannelMap.remove(uid);
        }
        userIdAndChannelID.remove(channel.id().asShortText());
    }


    public static Channel getToChanel(Msg msg) {

        return userIdAndChannelMap.get(msg.getTo());
    }

}
